package com.beok.android.joylife.utils;

import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtil {
	
	private static String sdPath;
	
	static {
		sdPath = Environment.getExternalStorageDirectory() + "/";
	}
	
	public static String getSdPath() {
		return sdPath;
	}

	public static File createSdFile(String packageName,String fileName) throws IOException {
		File file = new File(sdPath + packageName + "/" + fileName);
		file.createNewFile();
		return file;

	}


	public static void createSdDir(String packageName) {
		File savDir = new File(sdPath + packageName);
		if(!savDir.exists()) 
			savDir.mkdirs();
	}


	public static boolean isFileExist(String packageName,String fileName) {
		File file = new File(sdPath + packageName + "/" + fileName);
		return file.exists();
	}


	public static boolean isFileExist(String path) {
        File file = new File(path);
        return file.exists();
    }

	public static File write2SDFromInput(String packageName, String fileName,InputStream input) {
		File file = null;
		OutputStream output = null;
		try {
		
			createSdDir(packageName);
			
			file = createSdFile(packageName, fileName);
			
			output = new FileOutputStream(file);
		
			byte buffer[] = new byte[4 * 1024];
			
			int len = 0;
			while ((len=input.read(buffer)) != -1) {
				output.write(buffer, 0, len);
			}
			
			output.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return file;
	}
	public static String getFileName(String fullFileName){
		int index = fullFileName.lastIndexOf("/");
		return fullFileName.substring(index+1);
	}
    public  static  File getCacheFile(String imageUri){
        File cacheFile =  null ;
        try  {
            if  (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                File sdCardDir = Environment.getExternalStorageDirectory();
                String fileName = getFileName(imageUri);
                File dir =  new  File(sdCardDir.getCanonicalPath()
                        + AsynImageLoader.CACHE_DIR);
                if  (!dir.exists()) {
                    dir.mkdirs();
                }
                cacheFile =  new  File(dir, fileName);
//	                Log.i(TAG,  "exists:"  + cacheFile.exists() +  ",dir:"  + dir +  ",file:"  + fileName);
            }
        }  catch  (IOException e) {
            e.printStackTrace();
//	            Log.e(TAG,  "getCacheFileError:"  + e.getMessage());
        }
        return  cacheFile;
    }
}
